<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音乐系统 - 管理员登录</title>
    <link rel="stylesheet" href="res/layui/css/layui.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        .login-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.2);
            width: 450px;
            padding: 40px;
            position: relative;
            overflow: hidden;
        }
        .login-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .login-title {
            text-align: center;
            margin-bottom: 30px;
        }
        .login-title h2 {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
            font-weight: 600;
        }
        .login-title p {
            color: #999;
            font-size: 14px;
        }
        .admin-badge {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 6px 20px;
            border-radius: 20px;
            font-size: 14px;
            display: inline-block;
            margin-top: 15px;
            font-weight: 500;
        }
        .layui-form-item {
            margin-bottom: 25px;
        }
        .layui-form-label {
            width: 70px;
            padding: 12px 10px;
        }
        .layui-input-block {
            margin-left: 100px;
        }
        .layui-input {
            height: 45px;
            line-height: 45px;
            padding-left: 15px;
            border-radius: 6px;
            border: 1px solid #e6e6e6;
            transition: all 0.3s;
        }
        .layui-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
        }
        .submit-btn {
            width: 100%;
            height: 48px;
            font-size: 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 6px;
            font-weight: 500;
            letter-spacing: 1px;
            transition: all 0.3s;
        }
        .submit-btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }
        .layui-icon-music {
            font-size: 48px;
            color: #667eea;
            margin-bottom: 15px;
        }
        .switch-login {
            text-align: center;
            margin-top: 25px;
            color: #999;
            font-size: 14px;
        }
        .switch-login a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s;
        }
        .switch-login a:hover {
            text-decoration: underline;
        }
        .tips {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 25px;
            font-size: 13px;
            color: #856404;
            line-height: 1.6;
        }
        .tips strong {
            color: #664d03;
        }
        .create-btn {
            width: 100%;
            margin-bottom: 20px;
            background: #fff;
            border: 1px solid #667eea;
            color: #667eea;
            height: 45px;
            border-radius: 6px;
            transition: all 0.3s;
        }
        .create-btn:hover {
            background: #667eea;
            color: white;
        }
        .footer {
            text-align: center;
            margin-top: 30px;
            color: #999;
            font-size: 12px;
        }
        .error-message {
            color: #ff4d4f;
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .loading .layui-icon {
            font-size: 30px;
            color: #667eea;
            animation: rotate 1s linear infinite;
        }
        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        /* 注册页面专用样式 */
        .register-title {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px 8px 0 0;
            margin: -40px -40px 30px -40px;
            text-align: center;
        }
        .register-title h2 {
            color: white;
            font-size: 28px;
            margin-bottom: 5px;
        }
        .register-title p {
            color: rgba(255,255,255,0.8);
            font-size: 14px;
        }
        .register-badge {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 4px 15px;
            border-radius: 15px;
            font-size: 13px;
            display: inline-block;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <!-- 登录页面 -->
        <div id="loginPage">
            <div class="login-title">
                <i class="layui-icon layui-icon-music"></i>
                <h2>音乐系统</h2>
                <p>Music Management System</p>
                <span class="admin-badge">
                    <i class="layui-icon layui-icon-set"></i> 管理员登录
                </span>
            </div>

            <div class="tips">
                <i class="layui-icon layui-icon-tips"></i> 
                <strong>重要提示：</strong>请输入管理员账号和密码进行登录。
            </div>

            <form class="layui-form" lay-filter="adminLoginForm" id="loginForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">
                        <i class="layui-icon layui-icon-username"></i>
                    </label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" 
                               placeholder="请输入管理员账号" autocomplete="off" class="layui-input" id="username">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">
                        <i class="layui-icon layui-icon-password"></i>
                    </label>
                    <div class="layui-input-block">
                        <input type="password" name="password" required lay-verify="required" 
                               placeholder="请输入密码" autocomplete="off" class="layui-input" id="password">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn submit-btn" lay-submit lay-filter="adminLoginSubmit">
                            <i class="layui-icon layui-icon-login"></i> 立即登录
                        </button>
                    </div>
                </div>
            </form>

            <div class="switch-login">
                <span>还没有账号？</span>
                <a href="javascript:void(0)" onclick="showRegisterPage()">
                    <i class="layui-icon layui-icon-add-circle"></i> 立即注册
                </a>
            </div>
        </div>

        <!-- 注册页面 -->
        <div id="registerPage" style="display: none;">
            <div class="register-title">
                <h2>管理员注册</h2>
                <p>Register New Administrator Account</p>
                <span class="register-badge">
                    <i class="layui-icon layui-icon-user"></i> 创建新管理员账号
                </span>
            </div>

            <div class="tips">
                <i class="layui-icon layui-icon-tips"></i> 
                <strong>注册说明：</strong>请填写以下信息创建新的管理员账号。
            </div>

            <form class="layui-form" lay-filter="adminRegisterForm" id="registerForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">
                        <i class="layui-icon layui-icon-username"></i>
                    </label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" 
                               placeholder="请输入管理员账号" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">
                        <i class="layui-icon layui-icon-password"></i>
                    </label>
                    <div class="layui-input-block">
                        <input type="password" name="password" required lay-verify="required" 
                               placeholder="请输入密码" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn submit-btn" lay-submit lay-filter="adminRegisterSubmit">
                            <i class="layui-icon layui-icon-ok"></i> 注册账号
                        </button>
                    </div>
                </div>
            </form>

            <div class="switch-login">
                <a href="javascript:void(0)" onclick="showLoginPage()" style="color: #667eea;">
                    <i class="layui-icon layui-icon-return"></i> 返回登录
                </a>
            </div>
        </div>

        <div class="switch-login">
            <span>普通用户？</span>
            <a href="login.html">
                <i class="layui-icon layui-icon-user"></i> 切换到用户登录
            </a>
        </div>
        
        <div class="footer">
            <p>© 2025 音乐系统 - 专业音乐管理平台</p>
        </div>
    </div>

    <script src="res/layui/layui.js"></script>
    <script>
        // 动态设置API基础地址，解决跨域问题
        const API_BASE = window.location.port === '63342' ? 'http://localhost:8080' : 'http://localhost:8080';
        
        // 显示注册页面
        function showRegisterPage() {
            document.getElementById('loginPage').style.display = 'none';
            document.getElementById('registerPage').style.display = 'block';
        }
        
        // 显示登录页面
        function showLoginPage() {
            document.getElementById('registerPage').style.display = 'none';
            document.getElementById('loginPage').style.display = 'block';
        }
        
        layui.use(['form', 'layer'], function(){
            var form = layui.form;
            var layer = layui.layer;

            // 管理员注册表单提交
            form.on('submit(adminRegisterSubmit)', function(data){
                console.log('=== 管理员注册 ===');
                console.log('表单数据:', data.field);
                
                var loadIndex = layer.load(2, {shade: [0.3, '#000']});
                
                // 调用后端管理员注册接口
                fetch(API_BASE + '/admin/register', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data.field)
                })
                .then(res => {
                    console.log('响应状态:', res.status, res.statusText);
                    if (!res.ok) {
                        throw new Error('HTTP ' + res.status + ': ' + res.statusText);
                    }
                    return res.json();
                })
                .then(result => {
                    console.log('注册响应:', result);
                    layer.close(loadIndex);
                    
                    if(result.success) {
                        layer.alert(
                            result.message + '<br><br>请使用以下账号登录：<br>' +
                            '用户名：<strong>' + data.field.username + '</strong><br>' +
                            '密码：<strong>' + data.field.password + '</strong>',
                            {
                                icon: 1,
                                title: '注册成功',
                                btn: ['去登录']
                            },
                            function() {
                                // 清空表单并显示登录界面
                                document.getElementById('registerForm').reset();
                                showLoginPage();
                            }
                        );
                    } else {
                        layer.msg(result.message || '注册失败', {icon: 2});
                    }
                })
                .catch(err => {
                    console.error('❌ 注册错误:', err);
                    layer.close(loadIndex);
                    
                    var errorMsg = '注册请求失败！<br><br>';
                    
                    if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {
                        errorMsg += '<strong>网络连接失败</strong><br><br>';
                        errorMsg += '可能的原因：<br>';
                        errorMsg += '1. 后端服务未启动 <span style="color:red;">← 最常见</span><br>';
                        errorMsg += '2. 后端端口不是 8080<br>';
                        errorMsg += '3. 防火墙阻止了连接<br><br>';
                        errorMsg += '<strong>解决方法：</strong><br>';
                        errorMsg += '1. 请启动后端项目（IDEA 中运行 MusicSysApplication）<br>';
                        errorMsg += '2. 确认后端运行在 http://localhost:8080<br>';
                        errorMsg += '3. 浏览器访问 http://localhost:8080 测试连接<br>';
                    } else {
                        errorMsg += '错误信息：' + err.message + '<br><br>';
                        errorMsg += '请检查：<br>';
                        errorMsg += '1. 后端服务是否正常运行<br>';
                        errorMsg += '2. 数据库连接是否正常<br>';
                    }
                    
                    layer.alert(errorMsg, {icon: 2, title: '错误', area: ['500px', 'auto']});
                });
                
                return false;
            });
            
            // 管理员登录表单提交
            form.on('submit(adminLoginSubmit)', function(data){
                console.log('=== 管理员登录 ===');
                console.log('表单数据:', data.field);
                
                var loadIndex = layer.load(2, {shade: [0.3, '#000']});
                
                // 调用后端管理员登录接口验证账号密码
                fetch(API_BASE + '/admin/login', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data.field)
                })
                .then(res => {
                    console.log('响应状态:', res.status, res.statusText);
                    if (!res.ok) {
                        throw new Error('HTTP ' + res.status + ': ' + res.statusText);
                    }
                    return res.json();
                })
                .then(result => {
                    console.log('登录响应:', result);
                    layer.close(loadIndex);
                    
                    if(result.success) {
                        // 不再检查用户名是否为admin，只要是数据库中存在的管理员账号就可以登录
                        if(result.data) {
                            console.log('✅ 管理员登录成功');
                            // 保存管理员信息到localStorage
                            localStorage.setItem('userInfo', JSON.stringify(result.data));
                            localStorage.setItem('token', result.data.id || '');
                            localStorage.setItem('isAdmin', 'true'); // 额外标记
                            
                            layer.msg('管理员登录成功！正在跳转...', {icon: 1, time: 1500}, function(){
                                // 跳转到管理员后台
                                window.location.href = 'admin.html';
                            });
                        }
                    } else {
                        console.log('❌ 登录失败:', result.message);
                        layer.alert('登录失败：' + (result.message || '未知错误') + 
                                   '<br><br>提示：<br>' +
                                   '1. 请检查账号和密码是否正确<br>' +
                                   '2. 确认您输入的是管理员账号<br>' +
                                   '3. 如无管理员账号，请先注册<br>' +
                                   '4. 普通用户请<a href="login.html">切换到用户登录</a>', 
                                   {icon: 2, title: '登录失败'});
                    }
                })
                .catch(err => {
                    console.error('❌ 登录错误:', err);
                    layer.close(loadIndex);
                    
                    // 详细的错误提示
                    var errorMsg = '登录请求失败！<br><br>';
                    
                    if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {
                        errorMsg += '<strong>网络连接失败</strong><br><br>';
                        errorMsg += '可能的原因：<br>';
                        errorMsg += '1. 后端服务未启动 <span style="color:red;">← 最常见</span><br>';
                        errorMsg += '2. 后端端口不是 8080<br>';
                        errorMsg += '3. 防火墙阻止了连接<br><br>';
                        errorMsg += '<strong>解决方法：</strong><br>';
                        errorMsg += '1. 请启动后端项目（IDEA 中运行 MusicSysApplication）<br>';
                        errorMsg += '2. 确认后端运行在 http://localhost:8080<br>';
                        errorMsg += '3. 浏览器访问 http://localhost:8080 测试连接<br>';
                    } else if (err.message.includes('HTTP 4')) {
                        errorMsg += '<strong>请求错误</strong><br><br>';
                        errorMsg += '错误信息：' + err.message + '<br><br>';
                        errorMsg += '请点击上方按钮创建管理员账号<br>';
                    } else {
                        errorMsg += '错误信息：' + err.message + '<br><br>';
                        errorMsg += '请检查：<br>';
                        errorMsg += '1. 后端服务是否正常运行<br>';
                        errorMsg += '2. 数据库连接是否正常<br>';
                    }
                    
                    layer.alert(errorMsg, {icon: 2, title: '错误', area: ['500px', 'auto']});
                });
                
                return false;
            });
        });
    </script>
</body>
</html>